<?php

namespace app\models;

use yii;
use app\components\BaseActiveRecord;

/**
 * This is the model class for table "{{%region}}".
 *
 * @property integer $id
 * @property string $name
 * @property integer $parent_id
 * @property integer $level
 */
class Region extends BaseActiveRecord {
    /**
     * @inheritdoc
     */
    public static function tableName() {
        return '{{%region}}';
    }

    /**
     * @inheritdoc
     */
    public function rules() {
        return [
            [['name'], 'required'],
            [['parent_id', 'level'], 'integer'],
            [['name'], 'string', 'max' => 50]
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels() {
        return [
            'id' => 'ID',
            'name' => '名称',
            'parent_id' => '父级ID',
            'level' => '层级',
        ];
    }

    public static function getPickerData() {
        $provinceId = [1, 825, 2112, 2256, 3607];
        $province = static::find()->where(['id' => $provinceId])->indexBy('id')->asArray()->all();
        $cityList = static::find()->where(['parent_id' => array_keys($province)])->asArray()->all();
        $cityList = yii\helpers\ArrayHelper::map($cityList, 'id', 'name', 'parent_id');
        $data = [];
        foreach ($province as $item) {

            $children = $cityList[$item['id']];
            $data[] = [
                'value' => $item['id'],
                'text' => $item['name'],
                'children' => self::children($children),
            ];
        }

        return yii\helpers\Json::encode($data);
    }

    public static function children($children) {
        $data = [];
        foreach ($children as $id => $name) {
            $data[] = [
                'value' => $id,
                'text' => $name,
            ];
        }
        return $data;
    }
}
